package top.withu.gaof.freehope.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

/**
 * @author Gaofan
 * @date 2019年3月22日 下午4:44:48
 * @describe jdbc连接工具类
 */
public class JDBCUtils {

//	private static String connect;

	private static String driverClassName;

	private static String URL;

	private static String username;

	private static String password;

	private static boolean autoCommit;

	private static Logger logger = LoggerFactory.getLogger(JDBCUtils.class);

	/** 声明一个 Connection类型的静态属性，用来缓存一个已经存在的连接对象 */
	private static Connection conn;

	// 获取配置，进行连接
	static {
		init();
		load();
		connect();
	}

	/**
	 * 参数初始化
	 * 
	 * @throws IOException
	 */
	private static void init() {
		Properties properties = new Properties();
		try {
			properties.load(new ClassPathResource("JDBCProps.properties").getInputStream());
			logger.info("init params success!");
		} catch (IOException e) {
			logger.error("inti params error!", e);
		}
		driverClassName = properties.getProperty("driverClassName");
		URL = properties.getProperty("URL");
		username = properties.getProperty("username");
		password = properties.getProperty("password");
		autoCommit = Boolean.valueOf(properties.getProperty("autoCommit"));
	}

	/**
	 * 载入数据库驱动类
	 */
	private static boolean load() {
		try {
			Class.forName(driverClassName);
			logger.info("driver load success!");
			return true;
		} catch (ClassNotFoundException e) {
			logger.error("dirver load error!", e);
		}
		return false;
	}

	/**
	 * 创建数据库连接
	 */
	private static Connection connect() {
		load();
		try {
			conn = DriverManager.getConnection(URL, username, password);
			logger.info("conn success!");
		} catch (SQLException e) {
			logger.error("conn failed", e);
		}
		return conn;
	}

	/**
	 * 设置事务提交
	 */
	private static void transaction() {
		try {
			conn.setAutoCommit(autoCommit);
			logger.info("transaction commit success!");
		} catch (SQLException e) {
			logger.error("transaction commit failed!", e);
		}
	}

	public static String Test() {
		try {
			PreparedStatement ps = conn.prepareStatement("select * from gf_mini_photo");
			ResultSet rs = ps.executeQuery();
			StringBuffer sb = new StringBuffer();
			while (rs.next()) {
				sb.append(rs.getRow());
			}
			logger.info(">>>>" + sb);
		} catch (SQLException e) {
			logger.error("test error", e);
		}
		return "";
	}

	public static void main(String[] args) {
		JDBCUtils.Test();
		JDBCUtils.transaction();
	}
}
